package com.xzw.cameratest.activty;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaScannerConnection;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.AppCompatSeekBar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.android.business.adapter.DataAdapterImpl;
import com.android.business.adapter.DataAdapterInterface;
import com.android.business.entity.ChannelInfo;
import com.android.business.entity.RecordInfo;
import com.android.business.exception.BusinessException;
import com.android.dahua.dhplaycomponent.IMediaPlayListener;
import com.android.dahua.dhplaycomponent.IOperationListener;
import com.android.dahua.dhplaycomponent.IPTZListener;
import com.android.dahua.dhplaycomponent.ITalkListener;
import com.android.dahua.dhplaycomponent.PlayManagerProxy;
import com.android.dahua.dhplaycomponent.camera.PBCamera.CloudBasePBCamera;
import com.android.dahua.dhplaycomponent.camera.PBCamera.CloudBasePBParam;
import com.android.dahua.dhplaycomponent.camera.PBCamera.DPSPBCamera;
import com.android.dahua.dhplaycomponent.camera.PBCamera.DPSPBCameraParam;
import com.android.dahua.dhplaycomponent.camera.PBCamera.ExpressPBCameraParam;
import com.android.dahua.dhplaycomponent.camera.PBCamera.ExpressPbCamera;
import com.android.dahua.dhplaycomponent.camera.inner.Camera;
import com.android.dahua.dhplaycomponent.camera.inner.DPSRecordFile;
import com.android.dahua.dhplaycomponent.camera.inner.PlayBackInfo;
import com.android.dahua.dhplaycomponent.common.Err;
import com.android.dahua.dhplaycomponent.common.PlayStatusType;
import com.android.dahua.dhplaycomponent.common.RecordType;
import com.android.dahua.dhplaycomponent.windowcomponent.window.PlayWindow;
import com.dahua.permission.PermissionUtil;
import com.dahua.permission.constant.PermissionConstant;
import com.xzw.cameratest.BuildConfig;
import com.xzw.cameratest.R;
import com.xzw.cameratest.async.AsyncBuilder;
import com.xzw.cameratest.base.BaseActivity;
import com.xzw.cameratest.calendardialog.CalendarDialog;
import com.xzw.cameratest.calendardialog.DateBean;
import com.xzw.cameratest.common.CommonInfo;
import com.xzw.cameratest.common.Config;
import com.xzw.cameratest.utils.FileStorageUtil;
import com.xzw.cameratest.utils.SPUtils;
import com.xzw.cameratest.utils.TimeUtils;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class PlayBackActivity extends BaseActivity implements View.OnClickListener, CalendarDialog.OnClickListener, PermissionUtil.OnPermissionRequestListener {

    public static final String KEY_PlayBack_ChannelInfo = "channelInfo";
    public static final int KEY_Handler_Stream_Start_Request = 0;
    public static final int KEY_Handler_Stream_Played = 1;
    public static final int KEY_Handler_First_Frame = 2;
    public static final int KEY_Handler_Net_Error = 3;
    public static final int KEY_Handler_Play_Failed = 4;
    public static final int KEY_Handler_Play_End = 5;
    public static final int KEY_Handler_Bad_File = 6;
    public static final int KEY_Handler_Seek_Success = 7;
    public static final int KEY_Handler_Seek_Cross_Border = 8;
    public static final int KEY_Handler_Seek_failed = 9;
    public static final int KEY_Handler_Play_Time = 12;
    public static final int KEY_Handler_Play_UnKnown = 15;
    public static final int KEY_Handler_Play_Over = 17;
    private ImageView mIvBack;
    private ConstraintLayout mClTitle;
    private PlayWindow mPlayWindow;
    private TextView mTvDate;
    private ImageView mIvFullScreen;
    private TextView mTvScreenshots;
    private TextView mTvVideotape;
    private AppCompatSeekBar mSeekBar;
    /**
     * 默认设置为查询设备录像
     * 录像来源分为两种：设备录像（储存在设备中）、中心录像（储存在服务中）
     */
    private RecordInfo.RecordResource recordResource = RecordInfo.RecordResource.Device;
    private CalendarDialog mCalendarDialog;
    private PlayManagerProxy mPlayManager;
    private DataAdapterInterface dataAdapterInterface;
    private ChannelInfo mChannelInfo;
    private List<DPSRecordFile> dpsRecordFiles = new ArrayList<>();
    private List<RecordInfo> mRecordInfos = new ArrayList<>();
    private long mRecordStartTime = -1;
    private long mRecordEndTime = -1;
    private int mPermission;
    private PermissionUtil permissionUtil;
    protected String[] recordPath;

    private boolean isFull = false;
    private int mScreenHeight;
    private int mScreenWidth;
    private Calendar mCalendar;
    /**
     * seekBar拖动状态中进度条不随着播放时间更新
     */
    private boolean mIsSeekBarTouching = false;
    private int mTimeOffset;//实际回调时间与录像时间有差，修正一下

    public static void open(Context context, ChannelInfo channelInfo) {
        Intent intent = new Intent(context, PlayBackActivity.class);
        intent.putExtra(KEY_PlayBack_ChannelInfo, channelInfo);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_play_back;
    }

    @Override
    protected void initView() {
        mIvBack = findViewById(R.id.iv_back);
        mClTitle = findViewById(R.id.cl_title);
        mPlayWindow = findViewById(R.id.playWindow);
        mIvFullScreen = findViewById(R.id.iv_full_screen);
        mTvScreenshots = findViewById(R.id.tv_screenshots);
        mTvVideotape = findViewById(R.id.tv_videotape);
        mTvDate = findViewById(R.id.tv_date);
        mSeekBar = findViewById(R.id.seekBar);
        mIvBack.setOnClickListener(this);
        mTvDate.setOnClickListener(this);
        mIvFullScreen.setOnClickListener(this);
        mTvScreenshots.setOnClickListener(this);
        mTvVideotape.setOnClickListener(this);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsSeekBarTouching = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mIsSeekBarTouching = false;
                if (mPlayManager != null && mPlayManager.isPlaying(mPlayManager.getSelectedWindowIndex())) {
                    int progress = (int) (seekBar.getProgress() + mRecordInfos.get(0).getStartTime());
                    mPlayManager.seekByTime(mPlayManager.getSelectedWindowIndex(), progress);
                    mPlayManager.setCurrentProgress(mPlayManager.getSelectedWindowIndex(), progress);
                }

            }
        });
    }

    @Override
    protected void initData() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay()
                .getMetrics(metric);
        mScreenWidth = metric.widthPixels; // 屏幕宽度（像素）
        mScreenHeight = metric.heightPixels; // 屏幕高度（像素）
        mTvDate.setText(TimeUtils.getDateYMD(System.currentTimeMillis()));
    }

    @Override
    protected void doSomething() {
        permissionUtil = new PermissionUtil(this);
        mChannelInfo = (ChannelInfo) getIntent().getSerializableExtra(KEY_PlayBack_ChannelInfo);
        dataAdapterInterface = DataAdapterImpl.getInstance();
        mCalendar = Calendar.getInstance();
        mCalendarDialog = new CalendarDialog();
        mCalendarDialog.setOnClickListener(this);
        mPlayManager = new PlayManagerProxy();
        //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
        mPlayManager.init(this, mPlayWindow);
        //设置播放监听
        // set play monitor.
        mPlayManager.setOnMediaPlayListener(iMediaPlayListener);
        //设置窗口操作监听
        mPlayManager.setOnOperationListener(iOperationListener);

        // set the intercom monitor.
        mPlayManager.setOnTalkListener(new ITalkListener());

        //设置云台监听
        // set the cloud monitor.
        mPlayManager.setOnPTZListener(new IPTZListener());

        initCommonWindow();

    }

    /**
     * 初始化视频窗口
     */
    public void initCommonWindow() {
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mPlayWindow.getLayoutParams();
        lp.width = isFull ? mScreenHeight : mScreenWidth;
        lp.height = isFull ? mScreenWidth : mScreenHeight / 3;
        mPlayWindow.setLayoutParams(lp);
        mPlayWindow.forceLayout(lp.width, lp.height);
    }

    @Override
    protected void onResume() {
        super.onResume();
        replay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlay(mPlayManager.getSelectedWindowIndex());
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopAll();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayManager != null) {
            mPlayManager.unitPlayManager();
            mPlayManager = null;
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_full_screen) {
            switchScreen();
        } else if (id == R.id.tv_screenshots) {
            checkPermission(1);
        } else if (id == R.id.tv_videotape) {
            checkPermission(2);
        } else if (id == R.id.tv_date) {
            mCalendarDialog.setCalendar(mCalendar);
            mCalendarDialog.show(getSupportFragmentManager(), getClass().getName());
            getSupportFragmentManager().executePendingTransactions();
            mCalendarDialog.refreshMonthInfo();
        }
    }

    private void checkPermission(int permissionType) {
        mPermission = permissionType;
        List<String> permissionList = new ArrayList<>();
        switch (permissionType) {
            case 1:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));
                break;
            case 2:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));
                permissionList.addAll(Arrays.asList(PermissionConstant.MICROPHONE));
                break;
        }
        permissionUtil.requestPermissions(this, permissionList.toArray(new String[0]));
    }

    @Override
    public void onPermissionGranted() {
        switch (mPermission) {
            case 1:
                onClickCapture();
                break;
            case 2:
                onClickVideotape();
                break;
        }
    }

    @Override
    public void onPermissionDenied() {

    }

    @Override
    public void onPermissionSetting(boolean b) {

    }

    /**
     * 抓图
     */
    protected void onClickCapture() {
        if (!mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex())) return;
        int currentWindowIndex = mPlayManager.getSelectedWindowIndex();
        String path = FileStorageUtil.createSnapPath();
        int ret = mPlayManager.snapShot(currentWindowIndex, path, true);
        if (ret == Err.OK) {
            showToast(getResources().getString(R.string.screenshots_success) + path);
            MediaScannerConnection.scanFile(this, new String[]{path}, null, null);
        } else {
            showToast(getResources().getString(R.string.screenshots_failed));
        }
    }

    /**
     * 录像
     */
    protected void onClickVideotape() {
        if (mPlayManager.isRecording(mPlayManager.getSelectedWindowIndex())) {
            int ret = mPlayManager.stopRecord(mPlayManager.getSelectedWindowIndex());
            if (ret == Err.OK) {
                showToast(getString(R.string.recording_end));
                MediaScannerConnection.scanFile(this, recordPath, null, null);
                mTvVideotape.setSelected(false);
            }
        } else {
            if (!mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()) || mPlayManager.isPause(mPlayManager.getSelectedWindowIndex()))
                return;
            int currentWindowIndex = mPlayManager.getSelectedWindowIndex();
            recordPath = FileStorageUtil.createRecordPath();
            recordPath[0] = recordPath[0].replaceAll("dav", "mp4");
            int ret = mPlayManager.startRecord(currentWindowIndex, recordPath, RecordType.RECORDER_TYPE_MP4);
            if (ret == Err.OK) {
                showToast(getString(R.string.recording_start));
                MediaScannerConnection.scanFile(getApplicationContext(), recordPath, null, null);
                mTvVideotape.setSelected(true);
            }
        }
    }

    /**
     * 查询某月的每天是否有录像
     */
    private void queryRecordDate(final int year, final int month, final List<DateBean> dateBeans) {
        showProgressDialog();
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<String>() {
            @Override
            public String doInBackground() throws Exception {
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, month - 1, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                Date date = calendar.getTime();
                return dataAdapterInterface.queryRecordDate(mChannelInfo.getChnSncode(), recordResource, RecordInfo.RecordEventType.All, date.getTime() / 1000, maxDays);
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<String>() {
            @Override
            public void onSuccess(String s) {
                dismissProgressDialog();
                //设备有录像的日期
                String[] datesArray = s.split(",");
                boolean[] maskArray = new boolean[datesArray.length];
                for (int i = 0; i < datesArray.length; i++) {
                    maskArray[i] = datesArray[i].equals("1");
                }
                for (int i = 0, j = 0; i < dateBeans.size(); i++) {
                    if (!TextUtils.isEmpty(dateBeans.get(i).getShownDay())
                            && j < maskArray.length) {
                        dateBeans.get(i).setHadRecord(maskArray[j++]);
                    } else {
                        dateBeans.get(i).setHadRecord(false);
                    }
                }
                mCalendarDialog.notifyDataChanged();
            }

            @Override
            public void onError(BusinessException e) {
                dismissProgressDialog();
            }
        });

    }

    /**
     * 查询某天的录像
     */
    protected void queryRecord() {
        showProgressDialog();
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<List<RecordInfo>>() {
            @Override
            public List<RecordInfo> doInBackground() throws Exception {
                return dataAdapterInterface.queryRecord(mChannelInfo.getChnSncode(), recordResource, RecordInfo.RecordEventType.All,
                        TimeUtils.getStartTimeByDay(mCalendar) / 1000L, TimeUtils.getEndTimeByDay(mCalendar) / 1000L, RecordInfo.StreamType.All_Type);
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<List<RecordInfo>>() {
            @Override
            public void onSuccess(List<RecordInfo> list) {
                dismissProgressDialog();
                //每次选择日期播放后需要重置进度为0，否则可能会导致播放录像日期错误
                if (mPlayManager.isPlaying(mPlayManager.getSelectedWindowIndex())) {
                    mPlayManager.setCurrentProgress(mPlayManager.getSelectedWindowIndex(), 0);
                }
                if (list != null && list.size() > 0) {
                    mRecordInfos.clear();
                    mRecordInfos.addAll(list);
                    mRecordStartTime = mRecordInfos.get(0).getStartTime();
                    mRecordEndTime = mRecordInfos.get(mRecordInfos.size() - 1).getEndTime();
                    recordToDpsRecord();
                    startPlayBack();
                } else {
                    stopPlay(mPlayManager.getSelectedWindowIndex());
                }
            }

            @Override
            public void onError(BusinessException e) {
                dismissProgressDialog();
            }
        });
    }

    /**
     * 开始播放
     */
    private void startPlayBack() {
        if (mPlayManager != null) {
            mPlayManager.addCamera(mPlayManager.getSelectedWindowIndex(), createCamera());
            mPlayManager.playSingle(mPlayManager.getSelectedWindowIndex());
        }
    }

    private void recordToDpsRecord() {
        dpsRecordFiles.clear();
        long totalTime = 0;
        for (RecordInfo recordInfo : mRecordInfos) {
            totalTime += recordInfo.getEndTime() - recordInfo.getStartTime();
            DPSRecordFile dpsRecordFile = new DPSRecordFile();
            dpsRecordFile.setSsId(recordInfo.getSsId());
            dpsRecordFile.setFileHandler(recordInfo.getFileHandle());
            dpsRecordFile.setDiskId(recordInfo.getDiskId() == null ? "" : recordInfo.getDiskId());
            dpsRecordFile.setFileName(recordInfo.getFileName());
            dpsRecordFile.setRecordSource(3);
            dpsRecordFile.setBeginTime((int) recordInfo.getStartTime());
            dpsRecordFile.setEndTime((int) recordInfo.getEndTime());
            dpsRecordFiles.add(dpsRecordFile);
        }
        mSeekBar.setMax((int) totalTime);
    }

    private Camera createCamera() {
        if (BuildConfig.dssPlatform == 1) {
            CloudBasePBParam cloudBasePBParam = new CloudBasePBParam();
            String chnSnCode = null;
            if (mPlayManager != null) {
                chnSnCode = mChannelInfo.getChnSncode();
                cloudBasePBParam.setNeedBeginTime((int) (mPlayManager.getCurrentProgress(mPlayManager.getSelectedWindowIndex())));
            }
            cloudBasePBParam.setCameraID(chnSnCode);
            cloudBasePBParam.setStreamType(0);

            cloudBasePBParam.setDpRestToken(CommonInfo.getInstance().getEnvironmentInfo().getRestToken());
            cloudBasePBParam.setServerIP(SPUtils.getString(Config.IP, ""));
            cloudBasePBParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));

            if (recordResource == RecordInfo.RecordResource.Device) {
                cloudBasePBParam.setLocation("device");
                cloudBasePBParam.setPlayBackByTime(true);
                cloudBasePBParam.setBeginTime((int) mRecordStartTime);
                cloudBasePBParam.setEndTime((int) mRecordEndTime);
            } else {
                cloudBasePBParam.setLocation("cloud");
                cloudBasePBParam.setPlayBackByTime(false);
                cloudBasePBParam.setDPSRecordFiles(dpsRecordFiles);
            }

            cloudBasePBParam.setBackPlay(false);
            cloudBasePBParam.setUseHttps(CommonInfo.getInstance().getEnvironmentInfo().isHttps() ? 1 : 0);

            return new CloudBasePBCamera(cloudBasePBParam);
        } else if (BuildConfig.dssPlatform == 2) {
            ExpressPBCameraParam expressPBCameraParam = new ExpressPBCameraParam();
            String chnSnCode = null;
            if (mPlayManager != null) {
                chnSnCode = mChannelInfo.getChnSncode();
                expressPBCameraParam.setNeedBeginTime((int) (mPlayManager.getCurrentProgress(mPlayManager.getSelectedWindowIndex())));
            }
            expressPBCameraParam.setCameraID(chnSnCode);
            expressPBCameraParam.setStreamType(1);

            expressPBCameraParam.setDpRestToken(CommonInfo.getInstance().getEnvironmentInfo().getRestToken());
            expressPBCameraParam.setServerIP(SPUtils.getString(Config.IP, ""));
            expressPBCameraParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));
            if (!TextUtils.isEmpty("")) {
                expressPBCameraParam.setEncrypt(true);
                expressPBCameraParam.setPsk("");
            }
            if (recordResource == RecordInfo.RecordResource.Device) {
                expressPBCameraParam.setLocation("device");
                expressPBCameraParam.setPlayBackByTime(true);
                expressPBCameraParam.setBeginTime((int) mRecordStartTime);
                expressPBCameraParam.setEndTime((int) mRecordEndTime);
            } else {
                expressPBCameraParam.setLocation("cloud");
                expressPBCameraParam.setPlayBackByTime(false);
                expressPBCameraParam.setDPSRecordFiles(dpsRecordFiles);
            }
            expressPBCameraParam.setAuthorization(CommonInfo.getInstance().getEnvironmentInfo().getAuthorization());
            expressPBCameraParam.setUri("/evo-apigw/admin/API/SS/Playback/");
            expressPBCameraParam.setUser_client(6);
            expressPBCameraParam.setReset(0);
            expressPBCameraParam.setBackPlay(false);
            expressPBCameraParam.setUseHttps(CommonInfo.getInstance().getEnvironmentInfo().isHttps() ? 1 : 0);
            return new ExpressPbCamera(expressPBCameraParam);
        } else {
            DPSPBCameraParam dpspbCameraParam = new DPSPBCameraParam();
            String chnSnCode = null;
            if (mPlayManager != null) {
                chnSnCode = mChannelInfo.getChnSncode();
            }
            dpspbCameraParam.setCameraID(chnSnCode);

            try {
                dpspbCameraParam.setDpHandle(String.valueOf(dataAdapterInterface.getDPSDKEntityHandle()));
            } catch (BusinessException e) {
                e.printStackTrace();
            }
            PlayBackInfo info = new PlayBackInfo();
            info.setIsBack(false);
            if (mPlayManager != null)
                info.setNeedBeginTime((int) (mPlayManager.getCurrentProgress(mPlayManager.getSelectedWindowIndex())));
            if (recordResource == RecordInfo.RecordResource.Device) {
                info.setPlayBackByTime(true);
                info.setBeginTime((int) mRecordStartTime);
                info.setEndTime((int) mRecordEndTime);
            } else {
                info.setPlayBackByTime(false);
                info.setRecordFileList(dpsRecordFiles);
            }
            dpspbCameraParam.setPlayBackInfo(info);
            return new DPSPBCamera(dpspbCameraParam);
        }
    }

    /**
     * 打开伴音
     */
    private void openAudio(int winIndex) {
        mPlayManager.openAudio(winIndex);
    }

    /**
     * 关闭伴音
     */
    private void closeAudio(int winIndex) {
        mPlayManager.closeAudio(winIndex);
    }

    /**
     * 停止播放
     */
    private void stopPlay(int winIndex) {
        //单个窗口视频停止播放
        mPlayManager.stopSingle(winIndex);
        closeAudio(mPlayManager.getSelectedWindowIndex());
    }

    /**
     * 重新播放
     */
    private void replay() {
        mPlayManager.playCurpage();
    }

    /**
     * 所有窗口停止播放
     */
    private void stopAll() {
        mPlayManager.stopAll();
    }

    /**
     * 切换横竖屏
     */
    public void switchScreen() {
        if (isFull) {
            isFull = false;
            mClTitle.setVisibility(View.VISIBLE);
            mIvFullScreen.setImageResource(R.mipmap.icon_full_screen);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            isFull = true;
            mClTitle.setVisibility(View.GONE);
            mIvFullScreen.setImageResource(R.mipmap.icon_exit_full_screen);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
        initCommonWindow();
    }

    @Override
    public void onBackPressed() {
        if (isFull) {
            switchScreen();
        } else {
            this.finish();
        }
    }

    @SuppressLint("HandlerLeak")
    protected Handler mPlayBackHander = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case KEY_Handler_Stream_Start_Request:
                    break;
                case KEY_Handler_Stream_Played:
                    openAudio(mPlayManager.getSelectedWindowIndex());
                    break;
                case KEY_Handler_First_Frame:

                    break;
                case KEY_Handler_Net_Error:
                case KEY_Handler_Play_Failed:
                case KEY_Handler_Bad_File:
                case KEY_Handler_Play_UnKnown:
                case KEY_Handler_Play_Over:
                    stopPlay(mPlayManager.getSelectedWindowIndex());
                    mSeekBar.setProgress(0);
                    break;
                case KEY_Handler_Play_End:
//                    stopAll();
//                    mSeekBar.setProgress(0);
                    break;
                case KEY_Handler_Play_Time:
                    long time = (long) msg.obj;
                    long startTime = mRecordInfos.get(0).getStartTime();
                    if (time < startTime) {
                        if (mTimeOffset == 0) {
                            mTimeOffset = (int) Math.abs(mRecordInfos.get(0).getStartTime() - time);
                        }
                        time += mTimeOffset;
                    }
                    if (!mIsSeekBarTouching) {
                        mSeekBar.setProgress((int) (time - mRecordInfos.get(0).getStartTime()));
                    }
                    break;
                case KEY_Handler_Seek_Success:
                    break;
                case KEY_Handler_Seek_failed:
                    break;
                case KEY_Handler_Seek_Cross_Border:
                    showToast(getString(R.string.play_back_seek_cross_border));
                    stopPlay(mPlayManager.getSelectedWindowIndex());
                    break;
            }
        }
    };

    private IMediaPlayListener iMediaPlayListener = new IMediaPlayListener() {
        @Override
        public void onPlayeStatusCallback(int winIndex, final PlayStatusType type, int code) {
            if (type == PlayStatusType.eStreamStartRequest) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Stream_Start_Request);
            } else if (type == PlayStatusType.eStreamPlayed) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Stream_Played);
            } else if (type == PlayStatusType.ePlayFirstFrame) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_First_Frame);
            } else if (type == PlayStatusType.ePlayEnd) {
                if (mPlayBackHander != null) mPlayBackHander.sendEmptyMessage(KEY_Handler_Play_End);
            } else if (type == PlayStatusType.eNetworkaAbort) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Net_Error);
            } else if (type == PlayStatusType.ePlayFailed) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Play_Failed);
            } else if (type == PlayStatusType.eBadFile) {
                if (mPlayBackHander != null) mPlayBackHander.sendEmptyMessage(KEY_Handler_Bad_File);
            } else if (type == PlayStatusType.eStatusUnknow) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Play_UnKnown);
            } else if (type == PlayStatusType.ePlayOver) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Play_Over);
            } else if (type == PlayStatusType.eSeekSuccess) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Seek_Success);
            } else if (type == PlayStatusType.eSeekFailed) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Seek_failed);
            } else if (type == PlayStatusType.eSeekCrossBorder) {
                if (mPlayBackHander != null)
                    mPlayBackHander.sendEmptyMessage(KEY_Handler_Seek_Cross_Border);
            }

        }

        @Override
        public void onPlayerTimeAndStamp(int winIndex, long time, long timeStamp) {
            super.onPlayerTimeAndStamp(winIndex, time, timeStamp);
            Message msg = new Message();
            msg.what = KEY_Handler_Play_Time;
            msg.obj = time;
            if (mPlayBackHander != null) mPlayBackHander.sendMessage(msg);
        }
    };
    private IOperationListener iOperationListener = new IOperationListener() {

    };

    @Override
    public void onMonthChanged(int year, int month, List<DateBean> dateBeans) {
        queryRecordDate(year, month, dateBeans);
    }

    @Override
    public void onDateSelect(DateBean dateBean) {
        mCalendar = (Calendar) Calendar.getInstance().clone();
        mCalendar.set(dateBean.getYear(), dateBean.getMonth(), dateBean.getDay());
        mCalendarDialog.dismiss();
        mTvDate.setText(String.format(getString(R.string.calendar_date_day),
                dateBean.getYear(), dateBean.getMonth() + 1, dateBean.getDay()));
        if (dateBean.isHadRecord()) {
            queryRecord();
        } else {
            mPlayBackHander.sendEmptyMessage(KEY_Handler_Seek_Cross_Border);
        }
    }
}
